﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SiemensOPC;
using Opc.Ua;
using Opc.Ua.Client;
using VswService_V7.Config;
using VswService_V7.DataBase.Tables;
using System.Data;
using VswService_V7.Utility;
using VswService_V7.DataBase;
using VswService_V7.Print;

namespace VswService_V7.OPC.DB
{
    public class Is1AddressDbdata : SubscriptionDbDataBase
    {
        public Is1AddressDbdata(SimaticOPCClient opc, NodeConfig nodes) : base(opc, nodes)
        {
            _firstBatchNoAddress = opcNodes.Is1InputPipeAddress.Batch_No_1;
            _firstPipeNoAddress = opcNodes.Is1InputPipeAddress.Pipe_No_1;
            _firstPipeLenAddress = opcNodes.Is1InputPipeAddress.Pipe_Len_1;
        }

        string _Location = "IS1";

        string _firstBatchNoAddress = "";
        string _firstPipeNoAddress = "";
        string _firstPipeLenAddress = "";

        public override void CreateSubscription()
        {
            opcServer.QuickAddMonitorItem(opcNodes.Is1Address.GrpoupName,
                opcNodes.Is1Address.PublishTime,
                opcNodes.Is1Address.SampleTime,
                opcNodes.Is1Address.GetNodeAddress(),
                opcNodes.Is1Address.GetNodeDisplayName(),
                SubscriptionHandleIs);

            
        }

        volatile bool _lockRequest = false;
        private void SubscriptionHandleIs(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            try
            {
                MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
                if (notification == null || notification.Value.Value == null)
                    return;
                Console.WriteLine(_Location + "  REQUEST");
                if (monitoredItem.DisplayName == "Is_Request")
                {
                    bool ask;
                    if (bool.TryParse(notification.Value.Value.ToString(), out ask))
                    {
                        if (ask)
                        {
                            if(!_lockRequest)
                            {
                                _lockRequest = true;
                                Task.Run(() => SelectInputPipes());
                                Console.WriteLine(_Location + "请求读取 pipe");
                            }
                        }
                        else
                        {
                            Console.WriteLine("rest pipe_intput  Is_Response:");
                            _lockRequest = false;
                            opcServer.WriteValue("0", opcNodes.Is1Address.Is_Response);
                        }
                    }
                }

                if (monitoredItem.DisplayName == "Is_Request2")
                {
                    bool ask;
                    if (bool.TryParse(notification.Value.Value.ToString(), out ask))
                    {
                        if (ask)
                        {
                            if (!_lockRequest)
                            {
                                _lockRequest = true;
                                Task.Run(() => UpdateInputPipe());
                                Console.WriteLine(_Location + "请求更新 pipe");
                            }
                        }
                        else
                        {
                            Console.WriteLine("rest pipe_intput  Is_Response2:");
                            _lockRequest = false;
                            opcServer.WriteValue("0", opcNodes.Is1Address.Is_Response2);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private async Task SelectInputPipes()
        {
            await Task.Delay(500);

            try
            {
                string replaceAddress = "[1]";
                int count = 20;
                List<string> inputBatchNoAddress = new List<string>();
                List<string> inputPipeNoAddress = new List<string>();
                List<string> inputPipeLenAddress = new List<string>();
                for (int i = 0; i < count; i++)
                {
                    string newReplacedAddress = "[" + (i + 1).ToString() + "]";
                    //ns=7;s=S7300ET200M station_1.7+U03_KF1011.6T_BC4.NO1.Batch_ID
                    //ns=7;s=S7300ET200M station_1.7+U03_KF1011.6T_BC4.NO1.P_ID
                    string batchAddress = _firstBatchNoAddress.Replace(replaceAddress, newReplacedAddress);
                    string pipeAddress = _firstPipeNoAddress.Replace(replaceAddress, newReplacedAddress);
                    string lenAddress = _firstPipeLenAddress.Replace(replaceAddress, newReplacedAddress);
                    inputBatchNoAddress.Add(batchAddress);
                    inputPipeNoAddress.Add(pipeAddress);
                    inputPipeLenAddress.Add(lenAddress);
                }

                List<string> fullPipeNos = new List<string>();

                for (int i = 0; i < count; i++)
                {
                    string batchNo = opcServer.ReadNodeValue(inputBatchNoAddress[i]).Value.ToString();
                    string pipeNo = opcServer.ReadNodeValue(inputPipeNoAddress[i]).Value.ToString();

                    if (int.TryParse(batchNo, out int b) && int.TryParse(pipeNo, out int p))
                    {
                        if (b != 0 && p != 0)
                        {
                            int pipeNum = int.Parse(pipeNo);
                            string fullPipeNumber = batchNo + pipeNum.ToString("000");
                            fullPipeNos.Add(fullPipeNumber);
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                if (_lockRequest && fullPipeNos.Count > 0)
                {
                    var result = PIPE_INFO.SelectLastTimePipeLength(fullPipeNos);

                    // 暂时先 1= 成功  2=失败
                    if (result.Count == fullPipeNos.Count)
                    {
                        for(int i=0;i< result.Count;i++)
                        {
                            opcServer.WriteValue(result[i], inputPipeLenAddress[i]);
                        }
                        opcServer.WriteValue("1", opcNodes.Is1Address.Is_Response);
                    }
                    else
                    {
                        opcServer.WriteValue("2", opcNodes.Is1Address.Is_Response);
                    }
                }
                else
                {
                    opcServer.WriteValue("2", opcNodes.Is1Address.Is_Response);
                }

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("LoadInputPipe", ex);
                if (_lockRequest)
                {
                    opcServer.WriteValue("2", opcNodes.Is1Address.Is_Response);
                }

            }
        }

        private async Task UpdateInputPipe()
        {
            await Task.Delay(500);

            try
            {
                string replaceAddress = "[1]";
                int count = 20;
                List<string> inputBatchNoAddress = new List<string>();
                List<string> inputPipeNoAddress = new List<string>();
                List<string> inputPipeLenAddress = new List<string>();
                for (int i = 0; i < count; i++)
                {
                    string newReplacedAddress = "[" + (i + 1).ToString() + "]";
                    //ns=7;s=S7300ET200M station_1.7+U03_KF1011.6T_BC4.NO1.Batch_ID
                    //ns=7;s=S7300ET200M station_1.7+U03_KF1011.6T_BC4.NO1.P_ID
                    string batchAddress = _firstBatchNoAddress.Replace(replaceAddress, newReplacedAddress);
                    string pipeAddress = _firstPipeNoAddress.Replace(replaceAddress, newReplacedAddress);
                    string lenAddress = _firstPipeLenAddress.Replace(replaceAddress, newReplacedAddress);
                    inputBatchNoAddress.Add(batchAddress);
                    inputPipeNoAddress.Add(pipeAddress);
                    inputPipeLenAddress.Add(lenAddress);
                }

                List<string> batchNos = new List<string>();
                List<string> pipeNos = new List<string>();
                List<string> lengths = new List<string>();

                for (int i = 0; i < count; i++)
                {
                    string batchNo = opcServer.ReadNodeValue(inputBatchNoAddress[i]).Value.ToString();
                    string pipeNo = opcServer.ReadNodeValue(inputPipeNoAddress[i]).Value.ToString();
                    string length = opcServer.ReadNodeValue(inputPipeLenAddress[i]).Value.ToString();

                    if (int.TryParse(batchNo, out int b) && int.TryParse(pipeNo, out int p) && int.TryParse(length, out int l))
                    {
                        if(b!=0&&p!=0&&l!=0)
                        {
                            batchNos.Add(batchNo);
                            pipeNos.Add(pipeNo);
                            lengths.Add(length);
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }

                if(_lockRequest&&batchNos.Count>0)
                {
                    int result = PIPE_INFO.UpdatePipeInfoOnIs(batchNos,pipeNos,_Location,lengths);

                    // 暂时先 1= 成功  2=失败
                    if(result>0)
                    {
                        opcServer.WriteValue("1", opcNodes.Is1Address.Is_Response2);
                    }
                    else
                    {
                        opcServer.WriteValue("2", opcNodes.Is1Address.Is_Response2);
                    }
                }
                else
                {
                    opcServer.WriteValue("2", opcNodes.Is1Address.Is_Response2);
                }

            }
            catch(Exception ex)
            {
                LogHelper.WriteLog("LoadInputPipe", ex);
                if (_lockRequest)
                {
                    opcServer.WriteValue("2", opcNodes.Is1Address.Is_Response2);
                }
                    
            }
        }
    }
}
